﻿
//

//


using EMSNet.Core.Service;
using Microsoft.AspNetCore.Http;

namespace EMSNet.Service;

/// <summary>
/// 仪表管理服务 🧩
/// </summary>
[ApiDescriptionSettings(ServiceConst.GroupName, Order = 100)]
public class EmsDeviceService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<EmsDevice> _emsDeviceRep;
    private readonly ISqlSugarClient _sqlSugarClient;

    public EmsDeviceService(SqlSugarRepository<EmsDevice> emsDeviceRep, ISqlSugarClient sqlSugarClient)
    {
        _emsDeviceRep = emsDeviceRep;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 分页查询仪表管理 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询仪表管理")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<EmsDeviceOutput>> Page(PageEmsDeviceInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _emsDeviceRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.PollPointCode.Contains(input.Keyword) || u.DeviceCode.Contains(input.Keyword) || u.DeviceName.Contains(input.Keyword) || u.ProtoType.Contains(input.Keyword) || u.Address.Contains(input.Keyword) || u.Port.Contains(input.Keyword) || u.RequestMsg.Contains(input.Keyword) || u.MsgSlavel.Contains(input.Keyword) || u.OffsetFunction.Contains(input.Keyword) || u.OffsetPercent.Contains(input.Keyword) || u.OffsetDataVale.Contains(input.Keyword) || u.DataType.Contains(input.Keyword) || u.DataFormat.Contains(input.Keyword) || u.DataValue.Contains(input.Keyword) || u.DeviceValue.Contains(input.Keyword) || u.ReadTime.Contains(input.Keyword) || u.Status.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.PollPointCode), u => u.PollPointCode.Contains(input.PollPointCode.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.DeviceCode), u => u.DeviceCode.Contains(input.DeviceCode.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.DeviceName), u => u.DeviceName.Contains(input.DeviceName.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.ProtoType), u => u.ProtoType.Contains(input.ProtoType.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Address), u => u.Address.Contains(input.Address.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Port), u => u.Port.Contains(input.Port.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.RequestMsg), u => u.RequestMsg.Contains(input.RequestMsg.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.MsgSlavel), u => u.MsgSlavel.Contains(input.MsgSlavel.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.OffsetFunction), u => u.OffsetFunction.Contains(input.OffsetFunction.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.OffsetPercent), u => u.OffsetPercent.Contains(input.OffsetPercent.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.OffsetDataVale), u => u.OffsetDataVale.Contains(input.OffsetDataVale.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.DataType), u => u.DataType.Contains(input.DataType.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.DataFormat), u => u.DataFormat.Contains(input.DataFormat.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.DataValue), u => u.DataValue.Contains(input.DataValue.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.DeviceValue), u => u.DeviceValue.Contains(input.DeviceValue.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.ReadTime), u => u.ReadTime.Contains(input.ReadTime.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.Status), u => u.Status.Contains(input.Status.Trim()))
            .LeftJoin<EmsPollingPoint>((u, pollPointCode) => u.PollPointCode == pollPointCode.Code)
            .Select((u, pollPointCode) => new EmsDeviceOutput
            {
                Id = u.Id,
                TenantId = u.TenantId,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                CreateOrgId = u.CreateOrgId,
                CreateOrgName = u.CreateOrgName,
                IsDelete = u.IsDelete,
                PollPointCode = u.PollPointCode,
                PollPointCodeFkDisplayName = $"{pollPointCode.Name}",
                DeviceCode = u.DeviceCode,
                DeviceName = u.DeviceName,
                ProtoType = u.ProtoType,
                Address = u.Address,
                Port = u.Port,
                RequestMsg = u.RequestMsg,
                MsgSlavel = u.MsgSlavel,
                OffsetFunction = u.OffsetFunction,
                OffsetPercent = u.OffsetPercent,
                OffsetDataVale = u.OffsetDataVale,
                DataType = u.DataType,
                DataFormat = u.DataFormat,
                DataValue = u.DataValue,
                DeviceValue = u.DeviceValue,
                ReadTime = u.ReadTime,
                Status = u.Status,
            });
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取仪表管理详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取仪表管理详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<EmsDevice> Detail([FromQuery] QueryByIdEmsDeviceInput input)
    {
        return await _emsDeviceRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加仪表管理 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加仪表管理")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddEmsDeviceInput input)
    {
        var entity = input.Adapt<EmsDevice>();
        return await _emsDeviceRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新仪表管理 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新仪表管理")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateEmsDeviceInput input)
    {
        var entity = input.Adapt<EmsDevice>();
        await _emsDeviceRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除仪表管理 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除仪表管理")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteEmsDeviceInput input)
    {
        var entity = await _emsDeviceRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _emsDeviceRep.FakeDeleteAsync(entity);   //假删除
        //await _emsDeviceRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除仪表管理 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除仪表管理")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteEmsDeviceInput> input)
    {
        var exp = Expressionable.Create<EmsDevice>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _emsDeviceRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _emsDeviceRep.FakeDeleteAsync(list);   //假删除
        //return await _emsDeviceRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDataEmsDeviceInput input)
    {
        var pollPointCodeData = await _emsDeviceRep.Context.Queryable<EmsPollingPoint>()
            .InnerJoinIF<EmsDevice>(input.FromPage, (u, r) => u.Code == r.PollPointCode)
            .Select(u => new {
                Value = u.Code,
                Label = $"{u.Name}"
            }).ToListAsync();
        return new Dictionary<string, dynamic>
        {
            { "pollPointCode", pollPointCodeData },
        };
    }
    
    /// <summary>
    /// 导出仪表管理记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出仪表管理记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageEmsDeviceInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportEmsDeviceOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "仪表管理导出记录");
    }
    
    /// <summary>
    /// 下载仪表管理数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载仪表管理数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportEmsDeviceOutput>(), "仪表管理导入模板", (_, info) =>
        {
            if (nameof(ExportEmsDeviceOutput.PollPointCodeFkDisplayName) == info.Name) return _emsDeviceRep.Context.Queryable<EmsPollingPoint>().Select(u => $"{u.Name}").Distinct().ToList();
            return null;
        });
    }
    
    /// <summary>
    /// 导入仪表管理记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入仪表管理记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var stream = ExcelHelper.ImportData<ImportEmsDeviceInput, EmsDevice>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 采集点编码
                    var pollPointCodeLabelList = pageItems.Where(x => x.PollPointCodeFkDisplayName != null).Select(x => x.PollPointCodeFkDisplayName).Distinct().ToList();
                    if (pollPointCodeLabelList.Any()) {
                        var pollPointCodeLinkMap = _emsDeviceRep.Context.Queryable<EmsPollingPoint>().Where(u => pollPointCodeLabelList.Contains($"{u.Name}")).ToList().ToDictionary(u => $"{u.Name}", u => u.Code);
                        pageItems.ForEach(e => {
                            e.PollPointCode = pollPointCodeLinkMap.GetValueOrDefault(e.PollPointCodeFkDisplayName ?? "");
                            if (e.PollPointCode == null) e.Error = "采集点编码链接失败";
                        });
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        return true;
                    }).Adapt<List<EmsDevice>>();
                    
                    var storageable = _emsDeviceRep.Context.Storageable(rows)
                        .SplitError(it => it.Item.PollPointCode?.Length > 32, "采集点编码长度不能超过32个字符")
                        .SplitError(it => it.Item.DeviceCode?.Length > 32, "仪器编号长度不能超过32个字符")
                        .SplitError(it => it.Item.DeviceName?.Length > 32, "设备名称长度不能超过32个字符")
                        .SplitError(it => it.Item.ProtoType?.Length > 32, "协议长度不能超过32个字符")
                        .SplitError(it => it.Item.Address?.Length > 32, "IP/DIR长度不能超过32个字符")
                        .SplitError(it => it.Item.Port?.Length > 32, "Port长度不能超过32个字符")
                        .SplitError(it => it.Item.RequestMsg?.Length > 32, "RequestMsg长度不能超过32个字符")
                        .SplitError(it => it.Item.MsgSlavel?.Length > 32, "MsgSlavel长度不能超过32个字符")
                        .SplitError(it => it.Item.OffsetFunction?.Length > 32, "偏移公式长度不能超过32个字符")
                        .SplitError(it => it.Item.OffsetPercent?.Length > 32, "偏移系数长度不能超过32个字符")
                        .SplitError(it => it.Item.OffsetDataVale?.Length > 32, "偏移量长度不能超过32个字符")
                        .SplitError(it => it.Item.DataType?.Length > 32, "数据类型长度不能超过32个字符")
                        .SplitError(it => it.Item.DataFormat?.Length > 32, "数据格式长度不能超过32个字符")
                        .SplitError(it => it.Item.DataValue?.Length > 32, "值长度不能超过32个字符")
                        .SplitError(it => it.Item.DeviceValue?.Length > 32, "仪表值长度不能超过32个字符")
                        .SplitError(it => it.Item.ReadTime?.Length > 32, "读表时间长度不能超过32个字符")
                        .SplitError(it => it.Item.Status?.Length > 32, "状态长度不能超过32个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
